<!--
 * @Date: 2023-03-11 10:52:12
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-04-09 21:50:03
 * @FilePath: \A19\frontend\src\components\RunCode\ExpList.vue
-->
<!--
 * @Date: 2023-03-11 10:52:12
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-11 19:00:48
 * @FilePath: \A19\frontend\src\components\RunCode\ExpList.vue
-->
<template>
    <div class="list-container">
      <div class="head">
        实验
        <div>
          <ElButton plain type="primary" style="margin:10px;float:right;" @click="newExp" v-if="poss">新建实验</ElButton>
          <Transfer :getSelected="getSelected" :poss="poss" :datas="exps"/>
        </div>
      </div>
      
      <div style="height: calc(100% - 60px);">
        <el-table :data="filteredExps" style="width: 100%;height: calc(100% - 60px);">
          <el-table-column prop="name" label="实验名称"  sortable>
            <template #header>
              <el-input style="width: 200px;" v-model="search" size="default"  placeholder="搜索" />
              <!-- 考试名称 -->
            </template>
          </el-table-column>

          <el-table-column prop="startTime" label="开始时间" sortable>
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-icon><timer /></el-icon>
                <span style="margin-left: 10px">{{ (scope.row.startTime as Date).format('yyyy-MM-dd hh:mm:ss') }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间" sortable>
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-icon><timer /></el-icon>
                <span style="margin-left: 10px">{{ (scope.row.endTime as Date).format('yyyy-MM-dd hh:mm:ss') }}</span>
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="member" label="进入人数/总人数" width="200" /> -->
          <el-table-column prop="status" label="状态" >
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span style="margin-left: 0px" :style="{
                  color:(() =>{ 
                    if(scope.row.currentStatus === '未开始') return '#909399'
                    else if(scope.row.currentStatus === '已结束') return '#F56C6C'
                    else return '#67C23A'
                  })()
                }">{{ scope.row.currentStatus }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" :width="100">
            
            <!-- <template #default="scope" v-if="poss">
              <el-button v-if="scope.row.currentStatus === '进行中'" @click="watchOrJudge(scope.row._id)" link type="primary" size="small">{{ examOrHomework === 'exam'?'监考':'批阅' }}</el-button>
              <el-button v-if="scope.row.currentStatus === '未开始'" @click="editExOrHo(scope.row._id)" link type="primary" size="small">编辑</el-button>
              <el-button v-if="scope.row.currentStatus === '已结束'" @click="judgeExOrHo(scope.row._id)" link type="primary" size="small">批阅</el-button>
            </template>
            <template #default="scope" v-else>
              <el-button v-if="scope.row.currentStatus === '进行中' && !isDoneTest(scope.row._id)" @click="testOrHomework(scope.row._id)" link type="primary" size="small">{{ examOrHomework ===  'exam'?'进入考试':'开始答题' }}</el-button>
              <ElButton v-if="scope.row.currentStatus === '进行中' && isDoneTest(scope.row._id)" :disabled="true"  link type="primary" size="small">已提交</ElButton>
              <el-button v-if="scope.row.currentStatus === '未开始'" disabled link type="primary" size="small">{{ examOrHomework ===  'exam'?'进入考试':'开始答题' }}</el-button>
              <el-button v-if="scope.row.currentStatus === '已结束'" @click="checkPaper(scope.row._id)" link type="primary" size="small">查看</el-button>
            </template> -->
            <template #default="scope" v-if="poss">
                <ElButton @click="judgeExp(scope.row._id)" v-if="scope.row.currentStatus === '进行中'" type="primary" link size="small">批阅</ElButton>
                <ElButton @click="editExp(scope.row._id)" v-if="scope.row.currentStatus === '未开始'" type="primary" link size="small">编辑</ElButton>
                <ElButton @click="judgeExp(scope.row._id)" v-if="scope.row.currentStatus === '已结束'" type="primary" link size="small">批阅</ElButton>
            </template>
            <template #default="scope" v-else>
              <ElButton @click="exp(scope.row._id)" v-if="scope.row.currentStatus === '进行中' && !isDoneExp(scope.row._id)" type="primary" link size="small">开始答题</ElButton>
              <ElButton v-if="scope.row.currentStatus === '进行中' && isDoneExp(scope.row._id)" :disabled="true"  link type="primary" size="small">已提交</ElButton>
              <ElButton disabled v-if="scope.row.currentStatus === '未开始'" type="primary" link size="small">开始答题</ElButton>
              <ElButton @click="checkExp(scope.row._id)" v-if="scope.row.currentStatus === '已结束'" type="primary" link size="small">查看</ElButton>
            </template>
            
          </el-table-column>
        </el-table>
      </div>
      
    </div>
</template>

<script lang="ts" setup>
import { useClientStore } from "@/pinia/stores/client";
import { computed, ref, onMounted, reactive, inject,Ref } from 'vue';
import { storeToRefs } from 'pinia';
import { useRoute, useRouter } from 'vue-router';
import { experiment } from '../../shared/types/experiments';
import { courses } from "@/shared/types/courses";
import { Excel } from "@/utils/excel";

const courseInfo = inject<Ref<courses>>('courseInfo')

const store = useClientStore()
const {currentCourseId,currentUser,client} = storeToRefs(store)
const poss = computed(()=>{
    return currentUser.value.role === 'teacher'
})
const route = useRoute()
const router = useRouter()
const courseId =  route.params.courseId as string

const newExp = () =>{
    router.push({
        name:'createExp',
        params:{
            courseId:currentCourseId.value
        }
    })
    
}

const exps = reactive(new Array<theexperiment>())
const commitedExps = reactive(new Array<string>())
const isDoneExp = (expId:string):boolean =>{
  return commitedExps.find(e => e === expId)?true:false
}
const filteredExps = computed(() =>
    exps.filter(
    (data) =>
        !search.value ||
        data.name.toLowerCase().includes(search.value.toLowerCase())
    )
)
const search = ref('')

const editExp = (expId:string) =>{
    router.push({
        name:'editExp',
        params:{
            expId
        }
    })
}
const judgeExp = (expId:string) => {
  router.push({
        name:'judgeExp',
        params:{
            expId
        }
    })
}
const exp = (expId:string) =>{
  router.push({
        name:'experiment',
        params:{
            expId
        }
    })
}
const checkExp = (expId:string) =>{
  router.push({
    name:'checkExp',
    params:{
      expId
    }
  })
}

const getSelected = (list:string[]) =>{
  exportExcel(list)
}
const exportExcel = async (selectedList:string[]) =>{
  loadingInstance = ElLoading.service({
    target:'#app'
  })
  const ret = await client.value.callApi('Get/GetEInfo',{
    course:courseId,
    requiredExp:selectedList
  })
  if(ret.isSucc){
    console.log(ret.res);
    const data = {
      info:ret.res.info,
      students:ret.res.students.map((student,index,arr) =>{
        const scores = ret.res.info.map(test =>{
          const s = test.userExperiments.find(h => h.student === student._id)
          return s?s.score:0
        })
        // Reflect.deleteProperty(student,'_id')
        student._id = (index + 1).toString()
        return [...Object.values(student),...scores]
      })
    }
    Excel.exprotExcel((courseInfo?.value.name || '课程') + '实验' ,data,loadingInstance)
  }

}

let loadingInstance:any
onMounted(async () =>{
  loadingInstance = ElLoading.service({
    target:'#app'
  })
    if(!courseId){
        ElMessage.error('不存在')
        loadingInstance.close()
        router.back()
        return
    }
    currentCourseId.value = courseId
    const ret = await client.value.callApi('Experiment/GetExp',{
        course:currentCourseId.value
    })
    if(ret.isSucc){
        // console.log(ret.res.exps);
        ret.res.exps.forEach(exp => {
            exps.push(statusFormer(exp))
        })
    }

    const ret2 = await client.value.callApi('Experiment/GetUserExps',{
      student:currentUser.value._id
    })
    if(ret2.isSucc){
      if(ret2.res.exps){
        commitedExps.push(...ret2.res.exps)
      }
    }
    loadingInstance.close()
    
})
const statusFormer = (exp:experiment):theexperiment=>{
  const start = exp.startTime
  const end = exp.endTime
  let status = ''
  let color = ''
  if(new Date < start){
    color = '#909399'
    return {
      ...exp,
      currentStatus:'未开始'
    }
  }
  else if(new Date > end){
    color = '#F56C6C'
    return {
      ...exp,
      currentStatus:'已结束'
    }
  }
  else{
    color = '#67C23A'
    return {
      ...exp,
      currentStatus:'进行中'
    }
  }
}

interface theexperiment extends experiment{
  currentStatus:'进行中' | '未开始' | '已结束'
}
</script>

<style lang="less" scoped>

</style>